"""
pytest配置文件 - 公共测试固件和配置
"""

import pytest
import tempfile
import os
import json
from unittest.mock import MagicMock

@pytest.fixture
def temp_config_dir():
    """创建临时配置目录"""
    with tempfile.TemporaryDirectory() as tmpdir:
        yield tmpdir

@pytest.fixture
def sample_config():
    """示例配置数据"""
    return {
        "logging": {
            "level": "DEBUG",
            "file": "test.log"
        },
        "engine": {
            "max_workers": 5,
            "default_polling_interval": 1000
        },
        "database": {
            "sqlite": {
                "enabled": True,
                "path": ":memory:"
            }
        }
    }

@pytest.fixture
def sample_device_config():
    """示例设备配置"""
    return {
        "name": "TestPLC",
        "type": "modbus",
        "enabled": True,
        "connection": {
            "host": "127.0.0.1",
            "port": 502,
            "timeout": 3
        },
        "polling_interval": 1000,
        "data_points": [
            {
                "name": "temperature",
                "address": "40001",
                "data_type": "float",
                "access": "R",
                "description": "设备温度"
            }
        ]
    }

@pytest.fixture
def mock_modbus_client():
    """模拟Modbus客户端"""
    mock_client = MagicMock()
    mock_client.connect.return_value = True
    mock_client.is_socket_open.return_value = True
    mock_client.read_holding_registers.return_value = MagicMock(
        isError=lambda: False,
        registers=[27648]  # 模拟温度值
    )
    return mock_client

@pytest.fixture
def mock_database():
    """模拟数据库连接"""
    mock_db = MagicMock()
    mock_db.execute.return_value = True
    mock_db.fetchall.return_value = []
    return mock_db

@pytest.fixture
def sample_alarm_rule():
    """示例报警规则"""
    return {
        "device": "TestPLC",
        "tag": "temperature",
        "type": "threshold",
        "conditions": {
            "high": 80.0,
            "critical": 95.0
        },
        "message": "设备温度异常",
        "enabled": True
    }

@pytest.fixture(scope="session", autouse=True)
def setup_test_environment():
    """设置测试环境"""
    # 设置测试环境变量
    os.environ["TESTING"] = "1"
    os.environ["LOG_LEVEL"] = "DEBUG"
    
    yield
    
    # 清理测试环境
    os.environ.pop("TESTING", None)
    os.environ.pop("LOG_LEVEL", None) 